package me.fung.wubi.resource

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import mu.KotlinLogging
import java.io.File

open class LocalObject(
    private val path: String = "",
    private val prefix: String = "",
    private val suffix: String = "",
) {
    private val logger = KotlinLogging.logger { }

    fun path(): String = path

    init {
        if (path.isNotBlank()) {
            val file = File(path)
            if (!file.exists()) {
                file.mkdir()
            }
        }
    }

    val String.fullname: String get() = path + prefix + this + suffix

    inline fun <reified T> loadOrBuild(filename: String, noinline builder: (() -> T)? = null): T {
        return loadFromFile(filename) ?: builder?.invoke().also { save(filename, it) }
        ?: throw IllegalStateException("Cannot load file from ${filename.fullname}.")
    }

    inline fun <reified T> save(filename: String, data: T) {
        val str = Json.encodeToString(data)
        val file = File(filename.fullname)
        file.writeText(str)
    }

    inline fun <reified T> loadFromFile(filename: String): T? {
        val file = File(filename.fullname)
        if (file.exists()) {
            return Json.decodeFromString<T>(file.readText())
        }
        return null
    }

    inline fun <reified T> save(file: File, data: T) {
        val str = Json.encodeToString(data)
        file.writeText(str)
    }

    inline fun <reified T> loadFromFile(file: File): T? {
        if (file.exists()) {
            return Json.decodeFromString<T>(file.readText())
        }
        return null
    }

    fun exist(filename: String): Boolean {
        return File(filename.fullname).exists()
    }

}